package com.nlx.notes.module.service.impl.flow;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.nlx.notes.module.bean.bo.FlowMonthAmountStatisticsBO;
import com.nlx.notes.module.bean.dto.FlowPageQueryDTO;
import com.nlx.notes.module.bean.dto.TransactionsQueryDTO;
import com.nlx.notes.module.bean.dto.flow.FlowChangeDTO;
import com.nlx.notes.module.bean.dto.flow.FlowEditDTO;
import com.nlx.notes.module.bean.dto.flow.UpdateDBAmountDTO;
import com.nlx.notes.module.bean.dto.querydb.FlowDayQueryDTO;
import com.nlx.notes.module.bean.dto.querydb.FlowDayQueryDbDTO;
import com.nlx.notes.module.bean.vo.*;
import com.nlx.notes.module.bean.vo.accountbook.AccountBookVO;
import com.nlx.notes.module.bean.vo.category.CategoriesVO;
import com.nlx.notes.module.bean.vo.flow.FlowDetailVO;
import com.nlx.notes.module.bean.vo.flow.FlowQueryOverviewVO;
import com.nlx.notes.module.core.enums.FlowQueryTypeEnum;
import com.nlx.notes.module.core.enums.SystemKeyEnum;
import com.nlx.notes.module.core.enums.TransactionTypeEnum;
import com.nlx.notes.module.core.enums.error.FlowCodeEnum;
import com.nlx.notes.module.core.generator.IdGenerator;
import com.nlx.notes.module.core.util.AmountConverterUtils;
import com.nlx.notes.module.core.util.DataConvertorUtils;
import com.nlx.notes.module.core.util.DateUtils;
import com.nlx.notes.module.entity.*;
import com.nlx.notes.module.helper.flow.FlowEventHelper;
import com.nlx.notes.module.service.*;
import com.nlx.notes.module.service.flow.FlowManageService;
import com.nlx.notes.module.service.system.ISystemPreferencesService;
import com.nlx.notes.support.handler.exception.BusinessException;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Year;
import java.time.YearMonth;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class FlowManageServiceImpl implements FlowManageService {


    final IFlowDayStatisticsService flowDayStatisticsService;

    final IFlowMonthStatisticsService flowMonthStatisticsService;

    final IFlowYearStatisticsService flowYearStatisticsService;

    final ITransactionsService transactionsService;

    final IAccountsService accountsService;

    final ICategoriesService categoriesService;

    final FlowEventHelper flowEventHelper;

    final ISystemPreferencesService systemPreferencesService;

    final IAccountBooksService accountBooksService;


    @Override
    public FlowOverviewVo flowOverview(Long userId,Long bookId) {
        List<FlowOverviewVo> list = new ArrayList<>();
        //获取当前日期
        String currentDate = DateUtils.formatCurrentDate();
        //获取本月日期
        String currentMonth = DateUtils.formatCurrentMonth();
        //获取本年日期
        String currentYear = DateUtils.formatCurrentYear();
        LocalDate nowDate = LocalDate.now();
        String weekFirstDay = DateUtils.formatCurrentStartWeek(nowDate);
        String weekLastDay = DateUtils.formatCurrentEndWeek(nowDate);
        FlowDayStatistics dayStatistics = flowDayStatisticsService.findByDay(currentDate, userId,bookId);
        FlowOverviewVo floOverviewVo = new FlowOverviewVo();
        if (null != dayStatistics) {
            floOverviewVo.setExpendDayAmount(AmountConverterUtils.convertFenToYuan(dayStatistics.getExpense()));
            floOverviewVo.setIncomeDayAmount(AmountConverterUtils.convertFenToYuan(dayStatistics.getIncome()));
        }
        FlowMonthStatistics monthStatistics = flowMonthStatisticsService.findByMonth(currentMonth,bookId, userId);
        if (null != monthStatistics) {
            floOverviewVo.setExpendMonthAmount(AmountConverterUtils.convertFenToYuan(monthStatistics.getExpense()));
            floOverviewVo.setIncomeMonthAmount(AmountConverterUtils.convertFenToYuan(monthStatistics.getIncome()));
            floOverviewVo.setMonthBalance(AmountConverterUtils.convertFenToYuan(monthStatistics.getIncome() - monthStatistics.getExpense()));
        }
        FlowMonthAmountStatisticsBO flowMonthAmountStatisticsBO = transactionsService.sumByDate(weekFirstDay, weekLastDay, userId,bookId);
        if(null != flowMonthAmountStatisticsBO){
            floOverviewVo.setExpendWeekAmount(AmountConverterUtils.convertFenToYuan(flowMonthAmountStatisticsBO.getExpenseAmount()));
            floOverviewVo.setIncomeWeekAmount(AmountConverterUtils.convertFenToYuan(flowMonthAmountStatisticsBO.getIncomeAmount()));
        }
        FlowYearStatistics yearStatistics = flowYearStatisticsService.findByYear(currentYear,bookId, userId);
        if (null != yearStatistics) {
            floOverviewVo.setExpendYearAmount(AmountConverterUtils.convertFenToYuan(yearStatistics.getExpense()));
            floOverviewVo.setIncomeYearAmount(AmountConverterUtils.convertFenToYuan(yearStatistics.getIncome()));
        }
        //获取个人预算
        String monthBudgetStr = systemPreferencesService.findValueByKey(userId, SystemKeyEnum.USER_MONTH_BUDGET.getCode());
        if(StrUtil.isEmpty(monthBudgetStr)){
            monthBudgetStr = SystemKeyEnum.USER_MONTH_BUDGET.getDefaultValue();
        }
        int monthBudget = Integer.parseInt(monthBudgetStr);
        floOverviewVo.setMonthBudget(AmountConverterUtils.convertFenToYuan(monthBudget));
        int monthExpense = 0;
        if(null != monthStatistics ){
            monthExpense = monthStatistics.getExpense();
        }
        BigDecimal monthProgress = new BigDecimal(monthExpense).divide(new BigDecimal(monthBudget),2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
        floOverviewVo.setMonthProgress(monthProgress);
        return floOverviewVo;
    }

    @Override
    public PageResultVo<DayFlowViewVo> flowPage(FlowPageQueryDTO flowPageQueryDTO) {
        buildQueryTime(flowPageQueryDTO);
        //查询流水总数
        long transactionCount = transactionsService.countByCondition(flowPageQueryDTO);
        Pagination pagination = new Pagination(flowPageQueryDTO.getPage(), transactionCount, flowPageQueryDTO.getPageSize());
        if (0 == transactionCount) {
            return PageResultVo.success(pagination, Collections.emptyList());
        }
        //查询流水分页数据
        List<Transactions> transactionsList = transactionsService.pageByCondition(flowPageQueryDTO);
        if (CollUtil.isEmpty(transactionsList)) {
            return PageResultVo.success(pagination, Collections.emptyList());
        }
        //通过条件查询消费总额
        //组装返回结果
        List<DayFlowViewVo> dayFlowViewVoList = buildReposeFlowViewData(transactionsList, flowPageQueryDTO.getBookId(),flowPageQueryDTO.getUserId());
        return PageResultVo.success(pagination, dayFlowViewVoList);
    }

    private String buildResponseDate(FlowPageQueryDTO flowPageQueryDTO) {
        String responseDate ;
        String queryFlowType = flowPageQueryDTO.getQueryFlowType();
        if (FlowQueryTypeEnum.DAY.getCode().equalsIgnoreCase(queryFlowType)) {
            //组装当天日期
            responseDate = flowPageQueryDTO.getStartDate();
        } else if (FlowQueryTypeEnum.WEEK.getCode().equalsIgnoreCase(queryFlowType)) {
            responseDate = flowPageQueryDTO.getStartDate() + " - " + flowPageQueryDTO.getEndDate();
        } else if (FlowQueryTypeEnum.MONTH.getCode().equalsIgnoreCase(queryFlowType)) {
            responseDate = DateUtils.formatCurrentMonth();
        } else if (FlowQueryTypeEnum.YEAR.getCode().equalsIgnoreCase(queryFlowType)) {
            responseDate = DateUtils.formatCurrentYear();
        }else{
            responseDate = "总览";
        }
        return responseDate;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteFlow(Long id, Long userId) {
        //查询流水表中是否存存在数据
        TransactionsQueryDTO transactionsQueryDTO = new TransactionsQueryDTO();
        transactionsQueryDTO.setId(id);
        transactionsQueryDTO.setUserId(userId);
        Transactions transactions = transactionsService.findByCondition(transactionsQueryDTO);
        if (null == transactions) {
            log.error(" flow data not exist ,id -> {}", id);
            throw new BusinessException(FlowCodeEnum.FLOW_NOT_EXIST);
        }
        transactionsService.removeFlow(id);
        UpdateDBAmountDTO updateDBAmountDTO = new UpdateDBAmountDTO();
        updateDBAmountDTO.setAmount(-transactions.getAmount());
        updateDBAmountDTO.setDate(DateUtils.parseDate(transactions.getTransactionDate()));
        updateDBAmountDTO.setTransactionType(transactions.getTransactionType());
        updateDBAmountDTO.setUserId(userId);
        flowDayStatisticsService.deleteFlow(updateDBAmountDTO);
        flowYearStatisticsService.deleteFlow(updateDBAmountDTO);
        FlowChangeDTO flowChangeDTO = new FlowChangeDTO();
        flowChangeDTO.setFlowId(id);
        flowChangeDTO.setFlowNewDate(DateUtils.parseDate(transactions.getTransactionDate()));
        flowChangeDTO.setUserId(userId);
        flowEventHelper.flowChange(flowChangeDTO);
        return true;
    }

    @Override
    public FlowQueryOverviewVO flowQueryOverview(FlowPageQueryDTO flowPageQueryDTO) {
        buildQueryTime(flowPageQueryDTO);
        Integer expenseAmount = null;
        Integer incomeAmount = null;
        FlowQueryOverviewVO flowQueryOverviewVO = new FlowQueryOverviewVO();
        if(StrUtil.isEmpty(flowPageQueryDTO.getTransactionType())){
            flowPageQueryDTO.setTransactionType(TransactionTypeEnum.EXPEND.getCode());
            expenseAmount = transactionsService.findIncomeAmountByCondition(flowPageQueryDTO);
            //通过条件查询收入纵额
            flowPageQueryDTO.setTransactionType(TransactionTypeEnum.INCOME.getCode());
            incomeAmount = transactionsService.findIncomeAmountByCondition(flowPageQueryDTO);
            flowQueryOverviewVO.setBalance(AmountConverterUtils.convertFenToYuan(incomeAmount - expenseAmount));

        }else if(TransactionTypeEnum.EXPEND.getCode().equalsIgnoreCase(flowPageQueryDTO.getTransactionType())){
            flowPageQueryDTO.setTransactionType(TransactionTypeEnum.EXPEND.getCode());
            expenseAmount = transactionsService.findIncomeAmountByCondition(flowPageQueryDTO);
        }else if(TransactionTypeEnum.INCOME.getCode().equalsIgnoreCase(flowPageQueryDTO.getTransactionType())){
            flowPageQueryDTO.setTransactionType(TransactionTypeEnum.INCOME.getCode());
            incomeAmount = transactionsService.findIncomeAmountByCondition(flowPageQueryDTO);
        }
        if(null != expenseAmount){
            flowQueryOverviewVO.setTotalExpense(AmountConverterUtils.convertFenToYuan(expenseAmount));
        }
        if(null != incomeAmount){
            flowQueryOverviewVO.setTotalIncome(AmountConverterUtils.convertFenToYuan(incomeAmount));
        }

        flowQueryOverviewVO.setDate(buildResponseDate(flowPageQueryDTO));
        return flowQueryOverviewVO;
    }

    @Override
    public FlowDetailVO detail(Long flowId, Long userId) {
        TransactionsQueryDTO transactionsQueryDTO = new TransactionsQueryDTO();
        transactionsQueryDTO.setId(flowId);
        transactionsQueryDTO.setUserId(userId);
        Transactions transactions = transactionsService.findByCondition(transactionsQueryDTO);
        if (null == transactions) {
            return null;
        }
        FlowDetailVO flowDetailVO = DataConvertorUtils.copyProperties(transactions, FlowDetailVO::new);
        flowDetailVO.setFlowId(transactions.getId());
        String amount = AmountConverterUtils.convertFenToYuan(transactions.getAmount());
        //获取账号类型
        flowDetailVO.setAccountName(accountsService.findAccountNameByAccountId(transactions.getAccountId()));
        flowDetailVO.setCategoryName(categoriesService.findCategoryNameMapByCategoryId(transactions.getSecondCategoryId()));
        flowDetailVO.setAmount(amount);
        return flowDetailVO;
    }

    @Override
    public FlowDetailVO edit(FlowEditDTO flowEditDTO) {
        TransactionsQueryDTO transactionsQueryDTO = new TransactionsQueryDTO();
        transactionsQueryDTO.setId(flowEditDTO.getFlowId());
        transactionsQueryDTO.setUserId(flowEditDTO.getUserId());
        Transactions transactions = transactionsService.findByCondition(transactionsQueryDTO);
        if (null == transactions) {
            log.error(" flow data not exist ,id -> {}", flowEditDTO.getFlowId());
            throw new BusinessException(FlowCodeEnum.FLOW_NOT_EXIST);
        }
        String oldDate = transactions.getTransactionDate();
        transactions.setAmount(AmountConverterUtils.convertYuanToFen(flowEditDTO.getAmount()));
        transactions.setTransactionDate(DateUtils.formatDate(flowEditDTO.getTransactionDate()));
        transactions.setAccountId(flowEditDTO.getAccountId());
        transactions.setCategoryId(categoriesService.findParentIdByCategoryId(flowEditDTO.getCategoryId()));
        transactions.setSecondCategoryId(flowEditDTO.getCategoryId());
        transactions.setDescription(flowEditDTO.getDescription());
        transactions.setUpdatedAt(LocalDateTime.now());
        transactions.setDelFlag(0);
        boolean update = transactionsService.updateById(transactions);
        if(update){
            //触发事件
            FlowChangeDTO flowChangeDTO = new FlowChangeDTO();
            flowChangeDTO.setFlowId(flowEditDTO.getFlowId());
            flowChangeDTO.setFlowOldDate(DateUtils.parseDate(oldDate));
            flowChangeDTO.setFlowNewDate(flowEditDTO.getTransactionDate());
            flowChangeDTO.setUserId(flowEditDTO.getUserId());
            flowEventHelper.flowChange(flowChangeDTO);
        }
        return detail(flowEditDTO.getFlowId(), flowEditDTO.getUserId());
    }

    @Override
    public DayFlowViewVo findFlowDay(String dayDate,Long bookId, Long userId) {
        TransactionsQueryDTO transactionsQueryDTO = new TransactionsQueryDTO();
        transactionsQueryDTO.setUserId(userId);
        transactionsQueryDTO.setDayDate(dayDate);
        transactionsQueryDTO.setBookId(bookId);
        List<Transactions> transactionsList = transactionsService.findListByCondition(transactionsQueryDTO);
        if (CollUtil.isEmpty(transactionsList)) {
            return null;
        }
        List<DayFlowViewVo> dayFlowViewVoList = buildReposeFlowViewData(transactionsList,bookId, userId);
        if(CollUtil.isNotEmpty(dayFlowViewVoList)){
            return dayFlowViewVoList.get(0);
        }
        return null;
    }

    @Override
    public List<DayFlowViewVo> findFlowMonth(String month,Long bookId, Long userId) {
        if(null == userId){
            log.error("用户id为空");
            return Collections.emptyList();
        }
        LocalDate date = DateUtils.parseDate(month);
        String firstDay = DateUtils.formatFirstDayFortMonth(date);
        String endDay = DateUtils.formatLastDayForMonth(date);
        FlowDayQueryDbDTO flowDayQueryDTO = new FlowDayQueryDbDTO();
        flowDayQueryDTO.setUserId(userId);
        flowDayQueryDTO.setStartDate(firstDay);
        flowDayQueryDTO.setEndDate(endDay);
        flowDayQueryDTO.setBookId(bookId);
        List<FlowDayStatistics> list = flowDayStatisticsService.findListByCondition(flowDayQueryDTO);
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
//        List<DayFlowViewVo> dayFlowViewVoList = buildReposeFlowViewData(transactionsList, userId);
//        if(CollUtil.isNotEmpty(dayFlowViewVoList)){
//            return dayFlowViewVoList.get(0);
//        }
//        return null;




        return List.of();
    }

    /**
     * 组装流水返回的数据
     *
     * @param transactionsList 数据库查询到的数据
     * @return DayFlowViewVo
     */
    private List<DayFlowViewVo> buildReposeFlowViewData(List<Transactions> transactionsList,Long bookId, Long userId) {
        //解析出来流水的账号类型
        Set<Long> accountIds = transactionsList.stream().map(Transactions::getAccountId).collect(Collectors.toSet());
        Map<Long, String> accountMap = null;
        if (CollUtil.isNotEmpty(accountIds)) {
            //使用账号id查询账号信息列表
            accountMap = accountsService.findAccountMapByAccountIds(accountIds);
        }
        //获取到流水明细所属的天
        Set<String> dayTimes = transactionsList.stream().map(Transactions::getTransactionDate).collect(Collectors.toSet());
        //通过流水所属的天数查询天的统计数据
        List<FlowDayStatistics> dayStatisticsList = flowDayStatisticsService.findInDay(dayTimes,bookId,userId);
        if (CollUtil.isEmpty(dayStatisticsList)) {
            return Collections.emptyList();
        }
        Map<Long,CategoriesVO> cateGoryMap = null;
        //得到流水明细的分类ids
        Set<Long> categoryIds = transactionsList.stream().map(Transactions::getSecondCategoryId).collect(Collectors.toSet());
        if (CollUtil.isNotEmpty(categoryIds)) {
            List<CategoriesVO> categoriesList = categoriesService.findCategoryByCategoryIds(categoryIds);
            if(CollUtil.isNotEmpty(categoriesList)){
                cateGoryMap = categoriesList.stream()
                        .collect(Collectors.toMap(
                                CategoriesVO::getId,        // keyMapper
                                person -> person      // valueMapper，整个对象作为 value
                        ));
            }
        }
        //将流水按天进行分组
        Map<String, List<Transactions>> dayTransactionMap = transactionsList.stream().collect(Collectors.groupingBy(Transactions::getTransactionDate));
        List<DayFlowViewVo> dayFlowViewVoList = new LinkedList<>();
        for (String day : dayTimes) {
            List<Transactions> transactions = dayTransactionMap.get(day);
            DayFlowViewVo dayFlowViewVo = new DayFlowViewVo();
            dayFlowViewVo.setId(null);
            dayFlowViewVo.setDate(day);
            if (CollUtil.isNotEmpty(transactions)) {
                Pair<Integer, List<DayFlowDetailVo>> convertDetail =
                        this.convertDetail(transactions, accountMap, cateGoryMap);
                dayFlowViewVo.setRecords(convertDetail.getValue());
                dayFlowViewVo.setTotal(AmountConverterUtils.convertFenToYuan(convertDetail.getKey()));
            }
            dayFlowViewVoList.add(dayFlowViewVo);
        }
        dayFlowViewVoList.sort(Comparator.comparing(DayFlowViewVo::getDate).reversed());
        return dayFlowViewVoList;
    }


    private void buildQueryTime(FlowPageQueryDTO flowPageQueryDTO) {
        String queryFlowType = flowPageQueryDTO.getQueryFlowType();
        log.info("查询流水的类型:{}", queryFlowType);
        LocalDate nowDate = LocalDate.now();
        String startDate = flowPageQueryDTO.getStartDate();
        String endDate = flowPageQueryDTO.getEndDate();
        if (FlowQueryTypeEnum.DAY.getCode().equalsIgnoreCase(queryFlowType)) {
            //组装当天日期
            String currentDate = DateUtils.formatCurrentDate();
            startDate = currentDate;
            endDate = currentDate;
            flowPageQueryDTO.setResponseDate(currentDate);
        } else if (FlowQueryTypeEnum.WEEK.getCode().equalsIgnoreCase(queryFlowType)) {
            startDate = DateUtils.formatCurrentStartWeek(nowDate);
            endDate = DateUtils.formatCurrentEndWeek(nowDate);
            flowPageQueryDTO.setResponseDate(startDate + " - " + endDate);
        } else if (FlowQueryTypeEnum.MONTH.getCode().equalsIgnoreCase(queryFlowType)) {
            startDate = DateUtils.formatCurrentStartMonth(nowDate);
            endDate = DateUtils.formatCurrentEndMonth(nowDate);
        } else if (FlowQueryTypeEnum.YEAR.getCode().equalsIgnoreCase(queryFlowType)) {
            startDate = DateUtils.formatCurrentStartYear(nowDate);
            endDate = DateUtils.formatCurrentEndYear(nowDate);
        }else {
            if(!StrUtil.isEmpty(flowPageQueryDTO.getStartDate())){
                startDate = flowPageQueryDTO.getStartDate();
            }
            if(!StrUtil.isEmpty(flowPageQueryDTO.getEndDate())){
                endDate = flowPageQueryDTO.getEndDate();
            }
            if(StrUtil.isEmpty(startDate) && StrUtil.isNotEmpty(flowPageQueryDTO.getMonth())){
                YearMonth month = DateUtils.parseMonthDate(flowPageQueryDTO.getMonth());
                startDate = DateUtils.formatFirstDayFortMonth(month);
                endDate = DateUtils.formatLastDayForMonth(month);
            }
            if(StrUtil.isEmpty(startDate) && StrUtil.isNotEmpty(flowPageQueryDTO.getYear())){
                LocalDate year = DateUtils.parseYearDate(flowPageQueryDTO.getYear());
                startDate = DateUtils.formatFirstDayFortYear(year);
                endDate =  DateUtils.formatLastDayForYear(year);
            }
        }
        flowPageQueryDTO.setStartDate(startDate);
        flowPageQueryDTO.setEndDate(endDate);

        if(StrUtil.isNotEmpty(flowPageQueryDTO.getMinAmount())){
            flowPageQueryDTO.setMinAmountInt(AmountConverterUtils.convertYuanToFen(flowPageQueryDTO.getMinAmount()));
        }
        if(StrUtil.isNotEmpty(flowPageQueryDTO.getMaxAmount())){
            flowPageQueryDTO.setMaxAmountInt(AmountConverterUtils.convertYuanToFen(flowPageQueryDTO.getMaxAmount()));
        }
    }


    /**
     * 数据转换
     *
     * @param dayTransactions 流水数据
     * @param accountMap      账号信息
     * @param cateGoryMap     分类信息
     * @return DayFlowDetailVo
     */
    private Pair<Integer,List<DayFlowDetailVo>> convertDetail(List<Transactions> dayTransactions, Map<Long, String> accountMap,
                                                              Map<Long,CategoriesVO> cateGoryMap) {
        List<DayFlowDetailVo> dayFlowDetailVoList = new LinkedList<>();
        int amountSum = 0;
        for (Transactions transactions : dayTransactions) {
            DayFlowDetailVo dayFlowDetailVo = new DayFlowDetailVo();
            dayFlowDetailVo.setId(transactions.getId());
            dayFlowDetailVo.setTime(transactions.getTransactionTime());
            CategoriesVO categories = cateGoryMap.get(transactions.getSecondCategoryId());
            if(null != categories){
                dayFlowDetailVo.setCategoryName(categories.getName());
                dayFlowDetailVo.setCategoryIcon(categories.getCategoryIcon());
            }
            if(null != accountMap && null != accountMap.get(transactions.getAccountId())){
                dayFlowDetailVo.setAccountName(accountMap.get(transactions.getAccountId()));
            }
            dayFlowDetailVo.setAmount(AmountConverterUtils.convertFenToYuan(transactions.getAmount()));
            dayFlowDetailVo.setFlowType(transactions.getTransactionType());
            dayFlowDetailVo.setDescription(transactions.getDescription());
            int amount = transactions.getAmount();
            if(TransactionTypeEnum.EXPEND.getCode().equalsIgnoreCase(transactions.getTransactionType())){
                amount = -transactions.getAmount();
            }
            amountSum = amountSum + amount;
            dayFlowDetailVoList.add(dayFlowDetailVo);
        }
        return new Pair<>(amountSum,dayFlowDetailVoList);
    }


//    @PostConstruct
    public void test(){
        List<Transactions> transactionsList = transactionsService.list();
        log.info("开始设置流水的分类数据");
        for (Transactions transactions : transactionsList) {
            Long categoryId = categoriesService.findParentIdByCategoryId(transactions.getCategoryId());
            if(null != categoryId){
                transactionsService.update(Wrappers.lambdaUpdate(Transactions.class)
                        .set(Transactions::getCategoryId,categoryId)
                        .eq(Transactions::getId,transactions.getId()));
            }
        }
        log.info("分类设置完成");
    }

}
